package cn.gs.util.stream;

// @author gs
import java.io.IOException;
import java.io.Reader;

public class TokenReader {

    boolean[] bs = new boolean[256];

    public TokenReader(Reader r, String endChars) {
        this.r = r;
        for (int i = 0; i < endChars.length(); ++i) {
            char c = endChars.charAt(i);
            if (c < 256 && c >= 0) {
                bs[c] = true;
            }
        }
    }
    Reader r;
    String s = "";
    char cc = (char) -1;
    boolean isBack = false;

    String readToEndChar() throws IOException {
        if (cc == (char) -1) {
            cc = (char) r.read();
            if (cc == (char) -1) {
                throw new IOException("No more char for TokenReader");
            }
        }
        if (cc < 256 && cc >= 0 && bs[cc]) {
            String s = String.valueOf(cc);
            cc = (char) -1;
            return s;

        }
        StringBuilder sb = new StringBuilder();
        do {
            sb.append(cc);
            cc = (char) r.read();
        } while (cc != (char) -1 && (cc >= 256 || !bs[cc]));
        return sb.toString();
    }

    public void back() {
        isBack = true;
    }

    public boolean isEndChar(String s) {
        if (s != null && s.length() == 1) {
            char c = s.charAt(0);
            return bs[c];
        }
        return false;
    }

    public String get() throws IOException {
        if (isBack) {
            isBack = false;
        } else {
            s = readToEndChar();
        }
        return s;
    }
}
